package com.tegtech.api.system.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.tegtech.api.system.constant.UserConstants;
import com.tegtech.api.system.service.ISysPostService;
import com.tegtech.api.system.service.ISysRoleService;
import com.tegtech.api.system.service.ISysUserService;
import com.tegtech.common.domain.Result;
import com.tegtech.core.controller.BaseController;
import com.tegtech.core.page.PageResult;
import com.tegtech.module.auth.domain.SysRole;
import com.tegtech.module.auth.domain.SysUser;
import com.tegtech.starter.log.annotation.Log;
import com.tegtech.starter.log.enums.BusinessType;
import com.tegtech.starter.security.SecurityUtils;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.lang.Validator;

/**
 * 用户信息
 * 
 * @author Jun
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
	
	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysPostService postService;

	/**
	 * 获取用户列表
	 */
	@PreAuthorize("@ss.hasPermi('system:user:list')")
	@GetMapping("/list")
	public PageResult list(SysUser user) {
		return buildPageResult(() -> userService.selectUserList(user));
	}

	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('system:user:export')")
	@GetMapping("/export")
	public void export(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		exportExcel("用户数据", SysUser.class, list, "部门编号");
	}

	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	@PreAuthorize("@ss.hasPermi('system:user:import')")
	@PostMapping("/importData")
	public Result importData(MultipartFile file, boolean updateSupport) throws Exception {
		List<SysUser> userList = ExcelImportUtil.importExcel(file.getInputStream(), SysUser.class, new ImportParams());
		String operName = SecurityUtils.getUsername();
		String message = userService.importUser(userList, updateSupport, operName);
		return Result.ok().msg(message);
	}

	@GetMapping("/importTemplate")
	public void importTemplate() {
		exportExcel("用户数据导入模板", SysUser.class, Collections.emptyList(), "用户编号", "最后登陆IP", "最后登陆时间", "部门名称", "部门负责人");
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@PreAuthorize("@ss.hasPermi('system:user:query')")
	@GetMapping(value = { "/", "/{userId}" })
	public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		Map<String, Object> data = new HashMap<>(5);
		List<SysRole> roles = roleService.selectRoleAll();
		data.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
		data.put("posts", postService.selectPostAll());
		if (Validator.isNotNull(userId)) {
			data.put("user", userService.selectUserById(userId));
			data.put("postIds", postService.selectPostListByUserId(userId));
			data.put("roleIds", roleService.selectRoleListByUserId(userId));
		}
		return Result.ok().data(data);
	}

	/**
	 * 新增用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:add')")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@PostMapping
	public Result add(@Validated @RequestBody SysUser user) {
		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
			return Result.err().msg("新增用户'{}'失败，登录账号已存在", user.getUserName());
		} else if (Validator.isNotEmpty(user.getPhonenumber())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return Result.err().msg("新增用户'{}'失败，手机号码已存在", user.getUserName());
		} else if (Validator.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return Result.err().msg("新增用户'{}'失败，邮箱账号已存在", user.getUserName());
		}
		user.setCreateBy(SecurityUtils.getUsername());
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		return toResult(userService.insertUser(user));
	}

	/**
	 * 修改用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public Result edit(@Validated @RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		if (Validator.isNotEmpty(user.getPhonenumber())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return Result.err().msg("修改用户'{}'失败，手机号码已存在", user.getUserName());
		} else if (Validator.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return Result.err().msg("修改用户'{}'失败，邮箱账号已存在", user.getUserName());
		}
		user.setUpdateBy(SecurityUtils.getUsername());
		return toResult(userService.updateUser(user));
	}

	/**
	 * 删除用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:remove')")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
	public Result remove(@PathVariable Long[] userIds) {
		return toResult(userService.deleteUserByIds(userIds));
	}

	/**
	 * 重置密码
	 */
	@PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/resetPwd")
	public Result resetPwd(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		user.setUpdateBy(SecurityUtils.getUsername());
		return toResult(userService.resetPwd(user));
	}

	/**
	 * 状态修改
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/changeStatus")
	public Result changeStatus(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		user.setUpdateBy(SecurityUtils.getUsername());
		return toResult(userService.updateUserStatus(user));
	}
}
